<?php
include_once "class/WXBizMsgCrypt.php";

$token = $_REQUEST['token'];
$token = $token == "" ? "weixin" : $token;

$encodingAesKey = $_REQUEST['aes'];
$encodingAesKey = $encodingAesKey == "" ? "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C" : $encodingAesKey;

$corpId = $_REQUEST['corpId'];
$corpId = $corpId == "" ? "wx5823bf96d3bd56c7" : $corpId;

$url = $_REQUEST['url'];
$url = $url == "" ? "127.0.0.1/php/wefuck/weixin.php" : $url;

$sRespData = $_REQUEST['data'];
//$sRespData = "<xml><ToUserName><![CDATA[tname]]></ToUserName><FromUserName><![CDATA[fname]]></FromUserName><CreateTime>1445308274</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>1</AgentID></xml>";

$wxcpt = new WXBizMsgCrypt($token, $encodingAesKey, $corpId);

$sReqTimeStamp = time();
$sReqNonce = rand(1,999).time().rand(1,999);

// 需要发送的明文
$sEncryptMsg = ""; //xml格式的密文
$errCode = $wxcpt->EncryptMsg($sRespData, $sReqTimeStamp, $sReqNonce, $sEncryptMsg);
if ($errCode == 0) {
	// TODO:
	// 加密成功，企业需要将加密之后的sEncryptMsg返回
	// HttpUtils.SetResponce($sEncryptMsg);  //回复加密之后的密文
	echo $sEncryptMsg;
} else {
	print("ERR: " . $errCode . "\n\n");
	// exit(-1);
}

//密文中提取msg_signature
$sEncryptObj = simplexml_load_string($sEncryptMsg, 'SimpleXMLElement', LIBXML_NOCDATA);
$msg_signature = trim($sEncryptObj->MsgSignature);

$url = (strpos($url, "?") ? $url.'&' : $url.'?') . "signature=" . GetSignature( $token, $sReqTimeStamp, $sReqNonce ) . "&timestamp=" . $sReqTimeStamp . "&nonce=" . $sReqNonce . "&encrypt_type=aes&msg_signature=" . $msg_signature;
//exit;
$ch = curl_init();
$header[] = "Content-type: text/xml";//定义content-type为xml
curl_setopt($ch, CURLOPT_URL, $url); //定义表单提交地址
curl_setopt($ch, CURLOPT_POST, 1);   //定义提交类型 1：POST ；0：GET
curl_setopt($ch, CURLOPT_HEADER, 0); //定义是否显示状态头 1：显示 ； 0：不显示
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//定义请求类型
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);//定义是否直接输出返回流
curl_setopt($ch, CURLOPT_POSTFIELDS, $sEncryptMsg); //定义提交的数据，这里是XML文件
ob_start();
curl_exec($ch);
$result = ob_get_contents();
ob_end_clean();
curl_close($ch);//关闭
echo $result;

//获取signature
function GetSignature($token, $time, $random)
{
	$tmpArr = array($token, $time, $random);
	sort($tmpArr, SORT_STRING);
	$tmpStr = implode( $tmpArr );
	$tmpStr = sha1( $tmpStr );
	return $tmpStr;
}

